/*
 * @FileName: [VelocityUtil.java]
 * 
 * @Package com.bcinfo.iccard.admin.util
 * 
 * 
 * Copyright (c) 2011-2015 BCINFO Technology Limited Com.
 * All rights reserved.
 * 
 * This software is the confidential and proprietary
 * information of BCINFO Technology Limited Company
 * ("Confidential Information"). You shall not disclose
 * such Confidential Information and shall use it only
 * in accordance with the terms of the contract agreement
 * you entered into with RKY.
 * 
 * $Rev$
 * $LastChangedDate$
 * $LastChangedBy$
 * 
 * @category ICCARD
 * 
 * @version 1.1
 * 
 * @author $Author$
 * 
 * Change History:[Formatter: author date description] <br/>
 * 1
 * 2
 * 3
 */

package com.bcinfo.iccard.admin.util;

import java.io.File;
import java.io.PrintWriter;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.log4j.Logger;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

/**
 * velocity工具类 <br/>
 * <p>
 * Description:<br/>
 * <p>
 * 根据模板、路径、map 生成文件
 * 
 * <p>
 * For Examples <br/>
 * 
 * <PRE>
 *      ......
 * </PRE>
 * <p>
 */
public class VelocityUtil
{
    private static final Logger _log = Logger.getLogger(VelocityUtil.class);

    private static Properties   p    = new Properties();

    static
    {
        p.setProperty("resource.loader", "class");
        p.setProperty("class.resource.loader.class",
                "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    }

    public static void generateFile(Map<String, Object> map, String vmName, String path)
    {
        VelocityEngine engine = new VelocityEngine();
        PrintWriter write = null;

        try
        {
            engine.init(p);
            Template template = engine.getTemplate("vm/" + vmName, "UTF-8");

            VelocityContext veCntext = new VelocityContext();

            for (String key : map.keySet())
            {
                veCntext.put(key, map.get(key));
            }

            File file = new File(path);

            if (!file.exists())
            {
                file.mkdirs();
            }

            write = new PrintWriter(new File(path + "\\" + map.get("className")));

            template.merge(veCntext, write);

            write.flush();
        }
        catch (Exception e)
        {
            _log.error(ExceptionUtils.getStackTrace(e));
        }
        finally
        {
            if (write != null)
            {
                write.close();
            }
        }
    }
}